import { app, shell, BrowserWindow, session } from 'electron'
import { join } from 'path'
const os = require('os')

import axios from 'axios'
const reload = require('electron-reload')
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'

function formatTime(seconds) {
  //天
  const days = Math.floor(seconds / 86400);
    //时
  const hours = Math.floor(seconds / 3600);
    //分
  const minutes = Math.floor((seconds % 3600) / 60);

//渲染结果
  return `${days.toString().padStart(2, '0')}天:${hours.toString().padStart(2, '0')}时:${minutes.toString().padStart(2, '0')}分`;
}
















reload(__dirname)
function createWindow(): void {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    // 设置窗口尺寸
    width: 600,
    height: 900,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })




  const fetchdata = async()=>{
    //读取本地的jison文件中的资料   ，然后遍历处理
 await axios.get("http://170.106.186.229:300/tan/query").then(async(res)=>{

           //内容读出来
         const data = res.data
         //渲染出来数组
        

        //遍历出来
        data.sort((a: { id: number; },b: { id: number; })=>a.id-b.id)

   // console.log(data)
         for (let k in data){
          const uptime = os.uptime();

const formattedTime = formatTime(uptime);

 //遍历出来数据

           // 先排序
           const b=data[k]



         //声明内容  -指定的
 // console.log(b)
           const a = data[k].id
           const b1=b.remote




          //获取官方的区块高度
 await
 axios.get("http://node.dayuan0307.top:300/gf").then(async(gf)=>{
   const gd = gf.data

   // json中ip进行处理
     await axios.get(b1).then(resip=>{

       const bgd = resip.data.core_latest_ledger

     //开始逻辑处理
    const   c= gd-bgd
  //  console.log(c)
    const c1 = c<0 || c>1200
    const c2 = bgd===1
    const c3 = c>5000


    if(c1){
     axios.post("http://170.106.186.229:300/tan/ed",{
       id:a,
       status:"正常",
       uptime:formattedTime

     }).then(resa=>{


      //  console.log(2)
     }).catch(erra=>{

     })
    }
   if(c2){
     axios.post("http://170.106.186.229:300/tan/ed",{
       id:a,
       status:"新作",
       uptime:formattedTime
     }).then(resab=>{

     }).catch(errab=>{

     })
   }
  if(c3){
   axios.post("http://170.106.186.229:300/tan/ed",{
     id:a,
     status:"延迟",
     uptime:formattedTime
   }).then(resa=>{

   }).catch(erra=>{

   })

  }


     }).catch(
       err=>{
         axios.post("http://170.106.186.229:300/tan/ed",{
       id:a,
       status:"掉线",
       uptime:formattedTime
     }).then(resa=>{

       console.log("掉线")
     }).catch(erra=>{

     })
       }
     )
 })




         }

 })

     }
setInterval(()=>{
  fetchdata()

// },16000)
 },526000)
  // 快捷键设置
  mainWindow.webContents.on('before-input-event',(event,input)=>{
    if(input.key === 'F9'){
       mainWindow.webContents.openDevTools()
       reload(__dirname)

    }

  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })
  session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
    details.requestHeaders['Cache-Control'] = 'no-cache';
    callback({ cancel: false, requestHeaders: details.requestHeaders });
  })
  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })


  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}



// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')
















  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()



  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
